package com.wcar.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcar.common.entity.*;
import com.wcar.common.util.DistanceUtil;
import com.wcar.common.util.WebUtil;
import com.wcar.common.vo.Result;
import com.wcar.store.dao.*;
import com.wcar.store.service.StoreService;
import com.wcar.store.vo.AddressVo;
import com.wcar.store.vo.StoreVo;
import com.wcar.store.vo.UserVo;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: four-wcar-idea
 * @BelongsPackage: com.wcar.store.service.impl
 * @Author: 李睢康
 * @CreateTime: 2024-05-28  14:38
 */
@Service
public class StoreServiceImpl implements StoreService {
    @Resource
    private StoreDao storeDao;
    @Resource
    private LablesDao lablesDao;
    @Autowired
    private StringRedisTemplate template;
    @Resource
    private StoreUserDao storeUserDao;
    @Resource
    private EvaluateDao evaluateDao;
    @Resource
    private StantionDao stantionDao;
    @Resource
    private UserBalanceLogDao userBalanceLog;
    @Resource
    private UserIntegralLogDao userIntegralLog;
    @Resource
    private UserRoleDao userRoleDao;

    @Override
    public Result<IPage> getAll(StoreVo storeVo) {
        IPage<Store> iPage=new Page<>(storeVo.getCurrentPage(), storeVo.getPageSize());
        QueryWrapper<Store> queryWrapper=new QueryWrapper<>();
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = template.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        QueryWrapper<UserRole> wrapper1=new QueryWrapper<>();
        wrapper1.eq("user_id",user.getUserId());
        List<UserRole> userRoles = userRoleDao.selectList(wrapper1);
        ArrayList<Integer> roleIds=new ArrayList<>();
        for (UserRole u: userRoles) {
            roleIds.add(u.getRoleId());
        }
        if(!roleIds.contains(1)){
            QueryWrapper<StoreUser> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("user_id",user.getUserId());
            List<StoreUser> storeUsers = storeUserDao.selectList(queryWrapper1);
            ArrayList<Integer> storeIds = new ArrayList<>();
            for (StoreUser storeUser: storeUsers) {
                storeIds.add(storeUser.getStoreId());
            }
            if(!storeIds.isEmpty()){
                 queryWrapper.in("store_id",storeIds);
            }else {
                IPage<Store> iPage3 = storeDao.selectPage(iPage, queryWrapper);
                return new Result<IPage>(5000,"获取所有门店信息成功",null);
            }
        }
        if(storeVo.getStoreName()!=null&&storeVo.getStoreName()!=""){
            queryWrapper.like("store_name",storeVo.getStoreName());
        }
        IPage<Store> iPage1 = storeDao.selectPage(iPage, queryWrapper);
        return new Result<IPage>(200,"获取所有门店信息成功",iPage1);
    }

    @Override
    public Result<Integer> insert(Store store) {
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = template.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);

        store.setCreateBy(user.getUserName());
        Date date=new Date();
        store.setCreateTime(date);
        int insert = storeDao.insert(store);
        StoreUser storeUser = new StoreUser();
        storeUser.setStoreId(store.getStoreId());
        storeUser.setUserId(user.getUserId());
        storeUserDao.insert(storeUser);
        return new Result<>(200,"添加成功",insert);
    }

    @Override
    public Result<Integer> update(Store store) {
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = template.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        store.setUpdateBy(user.getUserName());
        Date date=new Date();
        store.setUpdateTime(date);
        int i = storeDao.updateById(store);
        return new Result<>(200,"编辑成功",i);
    }

    @Override
    public Result<Integer> delete(Integer storeId) {
        int delete = storeDao.deleteById(storeId);
        return new Result<>(200,"删除成功",delete);
    }

    @Override
    public Result<List<Store>> modelGetAll(AddressVo address) {
        String rectangle = address.getRectangle();
        String replace = rectangle.substring(0,7);
        String substring = rectangle.substring(12, 19);
        double w1 = Double.parseDouble(replace);
        double j1 = Double.parseDouble(substring);
        QueryWrapper<Store> wrapper=new QueryWrapper<>();
        if(address.getCity()!=null&&address.getCity()!=""){
            wrapper.eq("city",address.getCity());
        }
        if(address.getProvince()!=null&&address.getProvince()!=""){
            wrapper.eq("province",address.getProvince());
        }
        if(StringUtils.hasText(address.getStoreId())){
            wrapper.eq("ts.store_id",address.getStoreId());
        }

        List<Store> stores = storeDao.selectStore(wrapper);
        for (Store s: stores) {
            Double longitude = s.getLongitude();
            Double latitude = s.getLatitude();
            double distanceDouble1 = DistanceUtil.getDistanceDouble(w1, j1, longitude, latitude);
            double storeDistance=distanceDouble1/1000;
            String format = String.format("%.2f", storeDistance);
            double v = Double.parseDouble(format);
            s.setStoreDistance(v);
        }
        List<StoreLabels> storeLabels = lablesDao.selectList(null);
        for (Store s:stores) {
            ArrayList<String> storeLabel=new ArrayList<>();
            for (StoreLabels sl:storeLabels) {
                if(s.getStoreId().equals(sl.getStoreId())){
                    storeLabel.add(sl.getLabelContent());
                }
            }
            s.setStoreLabel(storeLabel);
        }
        List<StoreEvaluate> storeEvaluates = countAvg();
        for (Store s:stores) {
            for (StoreEvaluate se: storeEvaluates) {
                if(s.getStoreId().equals(se.getStoreId())){
                    s.setAverageStar(se.getAvg());
                }
            }
        }
        List<Station> stationNum = getStationNum();
        for (Store s:stores){
            for (Station ss: stationNum){
                if(ss.getStoreId().equals(s.getStoreId())){
                    s.setStationNumber(ss.getStationNumber());
                }
            }
        }
        List<Station> stationNums = getStationNums();
        for (Store s:stores){
            for (Station ss: stationNums){
                if(ss.getStoreId().equals(s.getStoreId())){
                    s.setStationIdle(ss.getStationNumber());
                }
            }
        }
        List<Station> stationNumss = getStationNumss();
        for (Store s:stores){
            for (Station ss: stationNumss){
                if(ss.getStoreId().equals(s.getStoreId())){
                    s.setStationUsed(ss.getStationNumber());
                }
                if(s.getStationUsed()==null){
                    s.setStationUsed(0);
                }
            }
        }
        return new Result<>(200,"获取所有门店信息成功",stores);
    }
    /**
     * 工位数量
    * */
    public List<Station> getStationNum(){
        return stantionDao.getStoreNum(null);
    }
    /**
     * 剩余工位数量
    **/
    public List<Station> getStationNums(){
        return stantionDao.getStoreNum(null);
    }
    /**
     * 正在使用工位数量
    * */
    public List<Station> getStationNumss(){
        List<Station> storeNum = stantionDao.getStoreNumUsed();
        return storeNum;
    }
    /**
     * 求店铺评价平均分
    * */
    private List<StoreEvaluate> countAvg(){
        List<StoreEvaluate> storeEvaluates = evaluateDao.selectAvg(null);
        return storeEvaluates;
    }
    @Override
    public Result<List<Store>> apisearchStore(UserVo userVo) {
        QueryWrapper<Store> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.like("store_name",userVo.getStoreName());
        List<Store> stores = storeDao.selectList(objectQueryWrapper);
        return new Result<>(200,"查询成功",stores);
    }

    @Override
    public Result<Store> selectByStoreId(String storeId) {
        QueryWrapper<Store> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("store_id",storeId);
        List<Store> stores = storeDao.selectList(objectQueryWrapper);
        Store store = stores.get(0);
        return new Result(200,"查询成功",store) ;
    }

    @Override
    public Result<List<Store>> selectNumByUserId(Integer userId) {
        QueryWrapper<Store> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Store> stores = storeDao.selectStoreById(userId);
        for (Store  a: stores) {
            Integer accountMoney = 0;
            try {
                QueryWrapper<UserBalanceLog> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("user_id",userId);
                wrapper1.eq("store_id",a.getStoreId());
                wrapper1 .select("sum(account_money) as accountMoney");
                UserBalanceLog userBalanceLog1 = userBalanceLog.selectOne(wrapper1);
                if(userBalanceLog1!=null){
                    accountMoney = userBalanceLog1.getAccountMoney();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            Integer accountMoney1 = 0;
            try {
                QueryWrapper<UserBalanceLog> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("user_id",userId);
                wrapper2.eq("store_id",a.getStoreId());
                wrapper2 .select("sum(expenditure) as expenditure");
                UserBalanceLog userBalanceLog2 = userBalanceLog.selectOne(wrapper2);
                if(userBalanceLog2!=null) {
                    accountMoney1 = userBalanceLog2.getExpenditure();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            a.setAmount(String.valueOf(accountMoney-accountMoney1));

            Integer expendScore = 0;
            try {
                QueryWrapper<UserIntegralLog> wrapper3 = new QueryWrapper<>();
                wrapper3.eq("user_id",userId);
                wrapper3.eq("store_id",a.getStoreId());
                wrapper3 .select("sum(expend_score) as expendScore");
                UserIntegralLog userIntegralLog1 = userIntegralLog.selectOne(wrapper3);
                if(userIntegralLog1!=null) {
                    expendScore = userIntegralLog1.getExpendScore();
                }
            } catch (Exception e) {

            }
            System.out.println(expendScore);
            Integer arrivalScore = 0;
            try {
                QueryWrapper<UserIntegralLog> wrapper4 = new QueryWrapper<>();
                wrapper4.eq("user_id",userId);
                wrapper4.eq("store_id",a.getStoreId());
                wrapper4 .select("sum(arrival_score) as arrivalScore");
                UserIntegralLog userIntegralLog1 = userIntegralLog.selectOne(wrapper4);
                if(userIntegralLog1!=null) {
                    arrivalScore = userIntegralLog1.getArrivalScore();
                }
            } catch (Exception e) {

            }
            System.out.println(arrivalScore);

            a.setCredits(String.valueOf(arrivalScore-expendScore));
        }
        return new Result<>(200,"查询店铺个数成功",stores);
    }


}
